<template>
  <el-tree-select :style="{
    width: proxy.$size(width, '100%'),
  }" v-model="keyword" v-bind="{
    placeholder: '请选择',
    clearable: true,
    props: {
      label: valueName,
      children: childrenName,
      isLeaf: 'isLeaf',
    },
    ...$attrs,
    disabled: typeof $attrs.disabled === 'function' ? $attrs.disabled(data) : $attrs.disabled
  }" :data="optionsArr" :render-after-expand="false" @change="changeBtn">
    <template #default="{ data }">
      {{ data[labelName] }}
    </template>
  </el-tree-select>
</template>
<script setup lang="ts">
import { getCurrentInstance, reactive, onMounted, ref } from 'vue';
const { proxy } = getCurrentInstance() as any;
//获取父级数据
const props = withDefaults(
  defineProps<{
    data: any;
    dataName?: any;
    width?: string | number;
    labelName?: string; //
    valueName?: string; //
    childrenName?: string; //
    disabledName?: string; //
    options?: any; //

  }>(),
  {
    type: '',
    labelName: 'label',
    valueName: 'value',
    disabledName: 'disabled',
    childrenName: 'children',
  },
);
const keyword = computed({
  get() {
    return props.dataName ? props.data[props.dataName] : props.data;
  },
  set(val) {
    if (props.dataName) {
      props.data[props.dataName] = val
    } else {
      props.data = val;
    }
  },
});
const optionsArr = computed(() => {
  let _arr: any[] = []
  if (Array.isArray(props.options)) {
    _arr = props.options.map((row) => {
      if (typeof row === "object") {
        return row
      } else {
        return {
          label: row,
          value: row,
        }
      }
    })
  } else if (typeof props.options === 'number') {
    _arr = Array.from({ length: props.options }).map((_, idx) => ({
      label: `选项${idx + 1}`,
      value: idx + 1,
    }))
  }
  return _arr
});

const emit = defineEmits<{
  //fn为父组件引入子组件是定义的子组件事件属性，可随意定义
  (event: 'changeBtn', val: any, form: any, rows?: any[]): void;
}>();
const changeBtn = (val: any) => {
  const _arr: any = childrenObj(optionsArr.value, val)
  emit('changeBtn', val, props.data, _arr)
};
const childrenObj = (arr: any, val: any) => {
  let _obj: any = null
  if (arr && arr.length > 0) {
    arr.forEach((el: any) => {
      if (el[props.valueName] === val) {
        _obj = {
          ...el
        }
      }
      const _childrenObj = childrenObj(el[props.childrenName], val)
      if (_childrenObj) {
        _obj = _childrenObj
      }
    });
  }
  return _obj
};


onMounted(() => { });
</script>
<style scoped></style>
